package com.sevenstudio.adu.gasing.object;

import org.andengine.extension.physics.box2d.PhysicsWorld;
import org.andengine.extension.physics.box2d.util.constants.PhysicsConstants;
import org.andengine.input.sensor.acceleration.AccelerationData;
import org.andengine.input.sensor.acceleration.IAccelerationListener;

import com.badlogic.gdx.math.Vector2;
import com.sevenstudio.adu.gasing.bluetooth.BT_Server_Client;
import com.sevenstudio.adu.gasing.engine.Anchor;
import com.sevenstudio.adu.gasing.engine.GameEngine;
import com.sevenstudio.adu.gasing.engine.Utils;

public class Mc extends Gasing implements IAccelerationListener
{
	boolean	move	= true;
	boolean sensor;
	
	public Mc(GameEngine gameEngine, GasingElement[] arrayGasing, int index, PhysicsWorld world, boolean sensor)
	{
		super(gameEngine, arrayGasing, index, world);
		this.sensor = sensor;
		if (sensor) engine.getEngine().enableAccelerationSensor(engine, this);
	}
	
	public void setMove(boolean move)
	{
		this.move = move;
	}
	
	public boolean isMove()
	{
		return move;
	}
	
	@Override
	public void reset()
	{
		super.reset();

		body.setTransform((Utils.GetAnchorX(Utils.GetRatio(gasing.getW()), Anchor.CENTER_LEFT) + Utils.GetRatio(200)) / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT,
				(Utils.GetAnchorY(Utils.GetRatio(gasing.getH()), Anchor.CENTER_LEFT) + Utils.GetRatio(0)) / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT, 0);
	}
	
	public void
			onAccelerationAccuracyChanged(AccelerationData pAccelerationData)
	{}
	
	public void onAccelerationChanged(AccelerationData pAccelerationData)
	{
		if (move && play)
		{
			if (!BT_Server_Client.isServer && BT_Server_Client.isBluetooth)
			{
				engine.server_Client.sendMessage("speedX," + getSpeedX(pAccelerationData.getX(), pAccelerationData.getY()) + "," + getSpeedY(pAccelerationData.getX(), pAccelerationData.getY()));
			}
			else
			{
				getBody().setLinearVelocity(
					new Vector2(getSpeedX(pAccelerationData.getX(), pAccelerationData.getY()), getSpeedY(pAccelerationData.getX(), pAccelerationData.getY())));
			}
		}
	}
	
	public void move(float speedX, float speedY)
	{
		if (!sensor) getBody().setLinearVelocity(new Vector2(speedX, speedY));
	}
}
